<template>
  <div class="singer-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>歌手管理</h2>
    </div>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <!-- 搜索框 -->
      <div class="search-box">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入歌手名称"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" :icon="Plus" @click="handleAddSinger">
          新增歌手
        </el-button>
        <el-button type="danger" :icon="Delete" @click="handleBatchDelete" :disabled="selectedSingers.length === 0">
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 歌手表格 -->
    <el-table
      :data="singerList"
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
      @selection-change="handleSelectionChange"
      border
    >
      <!-- 选择列 -->
      <el-table-column type="selection" width="55" />

      <!-- 歌手ID -->
      <el-table-column prop="singerId" label="ID" width="80" />

      <!-- 歌手头像 -->
      <el-table-column label="头像" width="120">
        <template #default="scope">
          <div class="singer-avatar">
            <el-image
                :src="getSingerImageUrl(scope.row.singerPic)"
                class="avatar-img"
                fit="cover"
                :preview-src-list="[getSingerImageUrl(scope.row.singerPic)]"
                preview-teleported
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <el-button
                type="primary"
                link
                :icon="Upload"
                @click="handleUpdateAvatar(scope.row)"
                class="update-avatar-btn"
            >
              更新
            </el-button>
          </div>
        </template>
      </el-table-column>

      <!-- 歌手姓名 -->
      <el-table-column prop="singerName" label="姓名" min-width="120" />

      <!-- 性别 -->
      <el-table-column label="性别" width="80">
        <template #default="scope">
          <el-tag
              v-if="scope.row.singerSex === 1"
              type="primary"
          >
            男
          </el-tag>
          <el-tag
              v-else-if="scope.row.singerSex === 0"
              type="success"
          >
            女
          </el-tag>
          <el-tag
              v-else
              type="warning"
          >
            组合
          </el-tag>
        </template>
      </el-table-column>

      <!-- 生日 -->
      <el-table-column prop="singerBirth" label="生日" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.singerBirth) }}
        </template>
      </el-table-column>

      <!-- 地区 -->
      <el-table-column prop="singerLocation" label="地区" width="120" />

      <!-- 简介 -->
      <el-table-column prop="singerIntro" label="简介" min-width="200" show-overflow-tooltip />

      <!-- 操作列 -->
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            link
            :icon="Edit"
            @click="handleEditSinger(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="primary"
            link
            :icon="Headset"
            @click="handleViewSongs(scope.row)"
          >
            歌曲
          </el-button>
          <el-button
            type="danger"
            link
            :icon="Delete"
            @click="handleDeleteSinger(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑歌手对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        :model="singerForm"
        :rules="singerRules"
        ref="singerFormRef"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="singerName">
          <el-input v-model="singerForm.singerName" placeholder="请输入歌手姓名" />
        </el-form-item>

        <el-form-item label="首字母" prop="singerFirstLetter">
          <el-input
              v-model="singerForm.singerFirstLetter"
              placeholder="请输入首字母"
              maxlength="1"
          />
        </el-form-item>

        <el-form-item label="性别" prop="singerSex">
          <el-radio-group v-model="singerForm.singerSex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
            <el-radio :label="2">组合</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="生日" prop="singerBirth">
          <el-date-picker
            v-model="singerForm.singerBirth"
            type="date"
            placeholder="请选择生日"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="地区" prop="singerLocation">
          <el-input v-model="singerForm.singerLocation" placeholder="请输入地区" />
        </el-form-item>

        <el-form-item label="简介" prop="singerIntro">
          <el-input
            v-model="singerForm.singerIntro"
            type="textarea"
            :rows="3"
            placeholder="请输入简介"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSingerForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 头像上传对话框 -->
    <el-dialog
      title="更新头像"
      v-model="avatarDialogVisible"
      width="400px"
    >
      <div class="avatar-upload-container">
        <el-upload
          class="avatar-uploader"
          drag
          :action="uploadAvatarUrl"
          :headers="uploadHeaders"
          :data="{ id: currentSinger?.singerId }"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          :before-upload="beforeAvatarUpload"
        >
          <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件，且不超过2MB
            </div>
          </template>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {Search, Plus, Delete, Edit, Headset, Upload, Picture} from '@element-plus/icons-vue'
import api from '@/services/api'
import singerDefaultAvatar from '@/assets/img/singer-default.png'
import { useRouter } from 'vue-router'
import { pinyin } from 'pinyin-pro'

export default {
  name: 'SingerPage',
  components: {
    Search,
    Plus,
    Delete,
    Edit,
    Headset,
    Upload,
    Picture
  },
  setup() {
    // 加载状态
    const loading = ref(false)
    const submitLoading = ref(false)

    // 路由
    const router = useRouter()

    // 搜索表单
    const searchForm = reactive({
      keyword: ''
    })

    // 歌手列表
    const singerList = ref([])

    // 选中的歌手
    const selectedSingers = ref([])

    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 5,
      total: 0
    })

    // 对话框相关
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const isEdit = ref(false)

    // 头像上传对话框
    const avatarDialogVisible = ref(false)
    const currentSinger = ref(null)

    // 歌手表单
    const singerForm = reactive({
      singerId: null,
      singerName: '',
      singerSex: 1,
      singerPic: '',
      singerBirth: '',
      singerLocation: '',
      singerIntro: '',
      singerFirstLetter: ''
    })

    // 表单验证规则
    const singerRules = {
      singerName: [
        { required: true, message: '请输入歌手姓名', trigger: 'blur' }
      ],
      singerSex: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ]
    }

    // 表单引用
    const singerFormRef = ref(null)

    // 默认头像
    const defaultAvatar = singerDefaultAvatar

    // 上传相关配置
    const uploadAvatarUrl = '/api/singer/singerOfPic'
    const uploadHeaders = {
      Authorization: localStorage.getItem('adminToken')
    }

    /**
     * 格式化日期
     * @param {string} date - 日期字符串
     * @returns {string} 格式化后的日期
     */
    const formatDate = (date) => {
      if (!date) return ''
      return date.split(' ')[0]
    }

    /**
     * 获取歌手列表
     */
    const fetchSingerList = async () => {
      loading.value = true
      try {
        let response
        if (searchForm.keyword) {
          // 模糊搜索
          response = await api.singer.search(searchForm.keyword)
        } else {
          // 获取所有歌手（分页）
          response = await api.singer.getAll({
            page: pagination.currentPage,
            size: pagination.pageSize
          })
        }

        if (response.code === '1') {
          singerList.value = response.data.list || response.data
          pagination.total = response.data.total || singerList.value.length
        } else {
          ElMessage.error(response.msg || '获取歌手列表失败')
          singerList.value = []
          pagination.total = 0
        }
      } catch (error) {
        ElMessage.error('获取歌手列表失败')
        console.error('Fetch singer list error:', error)
      } finally {
        loading.value = false
      }
    }

    /**
     * 处理搜索
     */
    const handleSearch = () => {
      pagination.currentPage = 1
      fetchSingerList()
    }

    /**
     * 处理选择变化
     * @param {Array} selection - 选中的行
     */
    const handleSelectionChange = (selection) => {
      selectedSingers.value = selection
    }

    /**
     * 处理分页大小变化
     * @param {number} val - 每页条数
     */
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      pagination.currentPage = 1
      fetchSingerList()
    }

    /**
     * 处理当前页变化
     * @param {number} val - 当前页码
     */
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      fetchSingerList()
    }

    /**
     * 获取字符串的首字母
     * @param {string} name - 歌手姓名
     * @returns {string} 首字母
     */
    const getFirstLetter = (name) => {
      if (!name || name.trim() === '') {
        return ''
      }

      // 使用 pinyin-pro 获取拼音
      try {
        // 获取第一个字符的拼音
        const firstChar = name.charAt(0)
        const pinyinResult = pinyin(firstChar, { toneType: 'none', type: 'array' })

        if (pinyinResult && pinyinResult.length > 0) {
          // 获取拼音的首字母并转为大写
          return pinyinResult[0].charAt(0).toUpperCase()
        } else {
          // 如果无法转换为拼音（如特殊字符），则使用原字符
          return firstChar.toUpperCase()
        }
      } catch (error) {
        console.error('获取拼音失败:', error)
        // 出错时返回原字符的大写形式
        return name.charAt(0).toUpperCase()
      }
    }

    /**
     * 处理新增歌手
     */
    const handleAddSinger = () => {
      dialogTitle.value = '新增歌手'
      isEdit.value = false
      // 重置表单
      Object.assign(singerForm, {
        singerId: null,
        singerName: '',
        singerSex: 1,
        singerBirth: '',
        singerLocation: '',
        singerIntro: '',
        singerFirstLetter: ''
      })
      dialogVisible.value = true
    }

    /**
     * 当歌手姓名改变时，自动获取首字母
     */
    const handleSingerNameChange = () => {
      if (singerForm.singerName && !isEdit.value) {
        singerForm.singerFirstLetter = getFirstLetter(singerForm.singerName)
      }
    }

    /**
     * 处理编辑歌手
     * @param {Object} row - 歌手数据
     */
    const handleEditSinger = (row) => {
      dialogTitle.value = '编辑歌手'
      isEdit.value = true
      // 确保正确填充所有表单数据
      Object.assign(singerForm, {
        singerId: row.singerId,
        singerName: row.singerName,
        singerSex: row.singerSex,
        singerBirth: row.singerBirth ? row.singerBirth.split(' ')[0] : '',
        singerLocation: row.singerLocation,
        singerIntro: row.singerIntro
      })
      dialogVisible.value = true
    }

    /**
     * 处理查看歌曲
     * @param {Object} row - 歌手数据
     */
    const handleViewSongs = (row) => {
      // 使用 Vue Router 进行页面跳转，并传递查询参数
      router.push({
        path: '/songList',
        query: { singerId: row.singerId }
      })
    }

    /**
     * 处理删除歌手
     * @param {Object} row - 歌手数据
     */
    const handleDeleteSinger = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除歌手 "${row.singerName}" 吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const response = await api.singer.delete(row.singerId)
        if (response.code === '1') {
          ElMessage.success('删除成功')
          await fetchSingerList()
        } else {
          ElMessage.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    /**
     * 处理批量删除
     */
    const handleBatchDelete = async () => {
      if (selectedSingers.value.length === 0) {
        ElMessage.warning('请先选择要删除的歌手')
        return
      }

      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedSingers.value.length} 个歌手吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        // 批量删除
        const deletePromises = selectedSingers.value.map(singer =>
          api.singer.delete(singer.singerId)
        )

        const results = await Promise.all(deletePromises)
        const successCount = results.filter(result => result.code === '1').length

        if (successCount > 0) {
          ElMessage.success(`成功删除 ${successCount} 个歌手`)
          await fetchSingerList()
        } else {
          ElMessage.error('删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    /**
     * 处理更新头像
     * @param {Object} row - 歌手数据
     */
    const handleUpdateAvatar = (row) => {
      currentSinger.value = row
      avatarDialogVisible.value = true
    }

    /**
     * 头像上传前检查
     * @param {File} file - 上传的文件
     * @returns {boolean} 是否允许上传
     */
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt10M) {
        ElMessage.error('头像图片大小不能超过 10MB!')
      }

      return isJPG && isLt10M
    }

    /**
     * 头像上传成功处理
     * @param {Object} response - 上传响应
     */
    const handleAvatarSuccess = (response) => {
      if (response.code === '1') {
        ElMessage.success('头像更新成功')
        avatarDialogVisible.value = false
        fetchSingerList()
      } else {
        ElMessage.error(response.msg || '头像更新失败')
      }
    }

    /**
     * 头像上传失败处理
     * @param {Error} error - 错误信息
     */
    const handleAvatarError = (error) => {
      ElMessage.error('头像上传失败')
      console.error('Avatar upload error:', error)
    }

    /**
     * 获取歌手图片完整URL
     * @param {string} imagePath - 图片相对路径
     * @returns {string} 完整图片URL
     */
    const getSingerImageUrl = (imagePath) => {
      // 如果没有图片路径，返回默认图片
      if (!imagePath) return defaultAvatar

      // 如果已经是完整URL则直接返回
      if (imagePath.startsWith('http')) {
        return imagePath
      }

      // 如果是绝对路径（以 / 开头），直接返回
      if (imagePath.startsWith('/')) {
        // 确保路径正确映射到静态资源
        return imagePath
      }

      // 如果是相对路径（如 img/singerPic/xxx.jpg）
      if (imagePath.startsWith('img/')) {
        return `/${imagePath}`
      }

      // 其他情况使用默认图片
      return defaultAvatar
    }

    /**
     * 提交歌手表单
     */
    const submitSingerForm = async () => {
      if (!singerFormRef.value) return

      await singerFormRef.value.validate(async (valid) => {
        if (valid) {
          // 添加调试信息
          console.log('Form validation passed, singerForm:', singerForm)
          // 前端额外校验
          if (!singerForm.singerName) {
            ElMessage.error('歌手姓名不能为空！')
            return
          }

          submitLoading.value = true
          try {
            let response
            if (isEdit.value) {
              // 编辑歌手时需要检查 singerId
              if (!singerForm.singerId) {
                ElMessage.error('歌手ID不能为空！')
                submitLoading.value = false
                return
              }
              // 编辑歌手
              const formData = {
                singerId: singerForm.singerId,
                singerName: singerForm.singerName,
                singerSex: singerForm.singerSex,
                singerBirth: singerForm.singerBirth,
                singerLocation: singerForm.singerLocation,
                singerIntro: singerForm.singerIntro,
                singerFirstLetter: singerForm.singerFirstLetter
              }
              console.log('Sending update data:', formData)
              response = await api.singer.update(formData)
            } else {
              if (!singerForm.singerFirstLetter) {
                singerForm.singerFirstLetter = getFirstLetter(singerForm.singerName)
              }
              // 新增歌手
              response = await api.singer.add({
                singerName: singerForm.singerName,
                singerSex: singerForm.singerSex,
                singerBirth: singerForm.singerBirth,
                singerLocation: singerForm.singerLocation,
                singerIntro: singerForm.singerIntro,
                singerFirstLetter: singerForm.singerFirstLetter
              })
            }

            if (response.code === '1') {
              ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
              dialogVisible.value = false
              await fetchSingerList()
            } else {
              ElMessage.error(response.msg || (isEdit.value ? '编辑失败' : '新增失败'))
            }
          } catch (error) {
            ElMessage.error(isEdit.value ? '编辑失败' : '新增失败')
            console.error('Submit singer form error:', error)
          } finally {
            submitLoading.value = false
          }
        }
      })
    }

    /**
     * 处理对话框关闭
     */
    const handleDialogClose = () => {
      if (singerFormRef.value) {
        singerFormRef.value.resetFields()
      }
    }

    // 组件挂载时获取数据
    onMounted(() => {
      fetchSingerList()
    })

    return {
      loading,
      submitLoading,
      searchForm,
      singerList,
      selectedSingers,
      pagination,
      dialogVisible,
      dialogTitle,
      isEdit,
      avatarDialogVisible,
      singerForm,
      singerRules,
      singerFormRef,
      defaultAvatar,
      uploadAvatarUrl,
      uploadHeaders,
      currentSinger,
      formatDate,
      handleSearch,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleAddSinger,
      handleEditSinger,
      handleViewSongs,
      handleDeleteSinger,
      handleBatchDelete,
      handleUpdateAvatar,
      beforeAvatarUpload,
      handleAvatarSuccess,
      handleAvatarError,
      submitSingerForm,
      handleDialogClose,
      getSingerImageUrl,
      handleSingerNameChange
    }
  }
}
</script>

<style scoped>
.singer-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.search-box {
  width: 300px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.singer-avatar {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
}

.update-avatar-btn {
  margin-top: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.avatar-upload-container {
  text-align: center;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}
</style>
